package com.rabbitmq.produce.callback;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangbowen
 * @date 2019/3/20
 **/
@Component
@Slf4j
public class ConfirmCallbackConfig {
    //implements RabbitTemplate.ConfirmCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    public final static Map<String, Map<String, Object>> messageMap = new ConcurrentHashMap<>();
   /* @PostConstruct
    private void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        System.out.println(correlationData);
        System.out.println(b);
        System.out.println(s);
    }*/

    @PostConstruct
    private void confirm() {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (StringUtils.isNotBlank(cause)) {
                if (correlationData != null) {
                    System.out.println(correlationData.getId());
                    System.out.println(ack);
                    System.out.println(cause);
                    Map<String, Object> map = messageMap.get(correlationData.getId());
                    rabbitTemplate.convertAndSend(String.valueOf(map.get("exchange")), String.valueOf(map.get("routingKey")), map.get("message"), correlationData);
                }
            } else {
                if (correlationData != null) {
                    if (!messageMap.isEmpty()) {
                        messageMap.remove(correlationData.getId());
                    }
                    log.info("确认成功,消息标识:{},确认结果:{}，{}", correlationData.getId(), ack, LocalDateTime.now().toString());
                }
            }
        });
    }
}
